package com.sunyard.manage.interceptor;

import com.sunyard.constant.ErrMessageConst;
import com.sunyard.constant.manage.CommonConst;
import com.sunyard.constant.manage.RegexConst;
import com.sunyard.constant.manage.SessionConstants;
import com.sunyard.dal.entity.OtherParam;
import com.sunyard.dal.entity.Popedom;
import com.sunyard.dal.mapper.OtherParamMapper;
import com.sunyard.manage.service.PopedomService;
import com.sunyard.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jiy.fang
 * @Description 登录拦截器
 * @date 2019/7/10
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PopedomService popedomService;

    @Autowired
    private OtherParamMapper otherParamMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("请求的uri:" + uri);
        int indexBegin = uri.indexOf("/", 2);
        if ("/login/login".equals(uri.substring(indexBegin))
                || "/login/logout".equals(uri.substring(indexBegin))
                || uri.contains("findPopedoms")
                || uri.contains("index")
                || uri.contains("appInterface")
                || "/manage/services".equals(uri)
                || "/login/checkLogin".equals(uri.substring(indexBegin))
                || uri.startsWith("/manage/hello")
                || "/manage/".equals(uri)
                || "/manage".equals(uri)
//                || uri.contains("/smartFee")
        ) {
            return true;
        }
        HttpSession session = request.getSession();
        // //Operator operator = (Operator) session.getAttribute(SessionConstants.OPERATOR);
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        OtherParam otherParam = otherParamMapper.queryByConfKey(OtherParam.SESSION_FAIL_TIME);
        session.setMaxInactiveInterval(Integer.parseInt(otherParam.getConfValue()) * 6000);
        //登录拦截
        if (session != null && opId != null) {
            String loginSessionId = redisTemplate.opsForValue().get("loginOperator:" + opId);
            if (loginSessionId != null && loginSessionId.equals(session.getId())) {
                if ("/login/updatePwd".equals(uri.substring(indexBegin)) || "/login/getOperatorInfo".equals(uri.substring(indexBegin))) {
                    return true;
                }
                //  进行url权限拦截
                if (false && !checkPopedom(session, uri)) {
                    log.info("url:" + uri + "没有通过权限验证");
                    responseNoPopedom(response);
                    return false;
                }
                return true;
            } else {
                responseOccupied(response);
                return false;
            }
        } else {
            // 用户未登录，跳转到登录页面。
            log.info("未通过session拦截器");
            responseNotLogIn(response);
            return false;
        }
    }

    private void responseNoPopedom(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print(CommonConst.getResult(CommonConst.NO_POPEDOM, "当前用户没有该操作权限"));
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
        }
    }

    private boolean checkPopedom(HttpSession session, String url) {
        //匹配url是否按照给定格式
        Pattern pattern = Pattern.compile(RegexConst.URL_REGEX);
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find()) {
            return false;
        }
        //获取当前上下文
        String currentLink = matcher.group();
        int len = currentLink.length();
        //去除当前上下文
        currentLink = currentLink.substring(7, len);
        //根据url剔除类型为3的URL
        int exist = popedomService.findPopedomByUrl(currentLink);
        if (exist > 0) {
            return true;
        }
        List<Popedom> popedomList = (List<Popedom>) session.getAttribute(SessionConstants.POPEDOM);
        for (Popedom popedom : popedomList) {
            String popedomLink = popedom.getPopedomLink();
            if (StringUtils.isNotBlank(popedomLink) && popedomLink.equals(currentLink)) {
                return true;
            }
        }
        return false;
    }

    private void responseNotLogIn(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print(CommonConst.getResult(CommonConst.NOT_LOGIN, "请重新登录"));
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
        }
    }

    private void responseOccupied(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print((CommonConst.getResult(CommonConst.OP_OCCUPIED, "账号已在其它地方登录")));
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
